﻿using System;
using System.Data;

namespace msBsc.WebUi
{
    public partial class wfCommGoodsList : msBsc.Cls.BPDealer
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindControls(); 
            }
        }

        private void BindControls()
        {
            if (!IsPostBack)
            {
            }
        }
        //重构基类的回调处理函数，以strAction属性来判断是什么类型的回调，该变量的值对应前台的ACTION参数，如：按钮的名称等
        public override void InitialByParam()
        {
            if (this.gtGridRet != null)
            {
                if (this.gtGridRet.action == "load" || this.gtGridRet.action == "export")//处理GRID的数据原获取和数据导出
                {
                    DataSet ds = GetDisplayData(this.GetParamHtValue("gtGridID"), this.strAction, this.sCurrPageRadom);
                    if (ds != null && ds.Tables.Count > 0)
                        SetReturnDatatable(ds.Tables[0], "GOODS_ID");//CONSTANT_CATEGORY_ID为表的KEY字段，可填可不填
                }
                ////处理数据保存
                //if (this.gtGridRet.action == "save" && (gtGridRet.insertedRecords.Length > 0 || gtGridRet.updatedRecords.Length > 0 || gtGridRet.deletedRecords.Length > 0))
                //{
                //    DataSet ds = GetDisplayData(this.GetParamHtValue("gtGridID"), this.strAction, this.sCurrPageRadom);
                //    try
                //    {
                //        if (ds != null && ds.Tables.Count > 0)
                //        {
                //            SetReturnDatatable(ds.Tables[0], "GOODS_ID");
                //            //处理记录新增，前台已传入新增的ROW
                //            for (int i = 0; i < gtGridRet.insertedRecords.Length; i++)
                //            {
                //                DataRow drNew = ds.Tables[0].NewRow();
                //                msBsc.AppLogic.Cfg.HttpTools.CopyHashToDataRow(gtGridRet.insertedRecords[i], drNew);
                //                drNew["GOODS_ID"] = (new Epm.AppLogic.Framework.CDbAccess()).NewID();
                //                ds.Tables[0].Rows.Add(drNew);
                //            }

                //            //处理记录更新，前台已传入更新的ROW
                //            for (int i = 0; i < gtGridRet.updatedRecords.Length; i++)
                //            {
                //                string stridtm = gtGridRet.updatedRecords[i]["GOODS_ID"].ToString();
                //                if (stridtm != string.Empty)
                //                {
                //                    DataRow[] arrtemr = ds.Tables[0].Select("GOODS_ID='" + stridtm + "'");
                //                    if (arrtemr.Length > 0)
                //                    {
                //                        msBsc.AppLogic.Cfg.HttpTools.CopyHashToDataRow(gtGridRet.updatedRecords[i], arrtemr[0]);
                //                    }
                //                }
                //            }

                //            //处理记录删除，前台已传入删除的ROW
                //            string strDelOneRowId = "";
                //            for (int i = 0; i < gtGridRet.deletedRecords.Length; i++)
                //            {
                //                string stridtm = gtGridRet.deletedRecords[i]["GOODS_ID"].ToString();
                //                if (stridtm != string.Empty)
                //                {
                //                    DataRow[] arrtemr = ds.Tables[0].Select("GOODS_ID='" + stridtm + "'");
                //                    if (arrtemr.Length > 0)
                //                    {
                //                        arrtemr[0].Delete();
                //                    }
                //                    strDelOneRowId += stridtm == "" ? stridtm : "," + stridtm;
                //                }
                //            }

                //            //DataSet dsTwo = null;
                //            //DataSet dsThree = null;

                //            //if (!string.IsNullOrEmpty(strDelOneRowId))
                //            //{



                //            //    string strDelTwoRowId = "";
                //            //    using (Epm.AppLogic.Framework.CDbAccess oCDbAccess = new Epm.AppLogic.Framework.CDbAccess())
                //            //    {
                //            //        string strSql = "SELECT * FROM SHP_COMMERCIAL_GOODS_LEVEL_TWO WHERE GOODS_ID IN ('" + strDelOneRowId.Replace(",", "','") + "')";
                //            //        DataSet dsTwoTemp = oCDbAccess.QueryBySQL(strSql);
                //            //        dsTwoTemp.Tables[0].TableName = "SHP_COMMERCIAL_GOODS_LEVEL_TWO";
                //            //        for (int i = 0; i < dsTwoTemp.Tables[0].Rows.Count; i++)
                //            //        {
                //            //            strDelTwoRowId += strDelTwoRowId == "" ? dsTwoTemp.Tables[0].Rows[i]["CT_LEVEL_TWO_ID"].ToString() : "," + dsTwoTemp.Tables[0].Rows[i]["CT_LEVEL_TWO_ID"].ToString();
                //            //        }
                //            //    }

                //            //    using (Epm.AppLogic.Framework.CDbAccess oCDbAccess = new Epm.AppLogic.Framework.CDbAccess())
                //            //    {
                //            //        string strSql = "SELECT * FROM SHP_COMMERCIAL_GOODS_LEVEL_THREE WHERE CT_LEVEL_TWO_ID IN ('" + strDelTwoRowId.Replace(",", "','") + "')";
                //            //        dsThree = oCDbAccess.QueryBySQL(strSql);
                //            //        dsThree.Tables[0].TableName = "SHP_COMMERCIAL_GOODS_LEVEL_THREE";
                //            //        for (int i = 0; i < dsThree.Tables[0].Rows.Count; i++)
                //            //        {
                //            //            dsThree.Tables[0].Rows[i].Delete();
                //            //        }

                //            //        strSql = "SELECT * FROM SHP_COMMERCIAL_GOODS_LEVEL_TWO WHERE CT_LEVEL_TWO_ID IN ('" + strDelTwoRowId.Replace(",", "','") + "')";
                //            //        dsTwo = oCDbAccess.QueryBySQL(strSql);
                //            //        dsTwo.Tables[0].TableName = "SHP_COMMERCIAL_GOODS_LEVEL_TWO";
                //            //        for (int i = 0; i < dsTwo.Tables[0].Rows.Count; i++)
                //            //        {
                //            //            dsTwo.Tables[0].Rows[i].Delete();
                //            //        }
                //            //    }
                //            //}


                //            if (ds.HasChanges())
                //            {
                //                System.Transactions.TransactionOptions transactionOption = new System.Transactions.TransactionOptions();
                //                transactionOption.IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted;
                //                transactionOption.Timeout = new TimeSpan(0, 10, 0);
                //                using (System.Transactions.TransactionScope ts = new System.Transactions.TransactionScope(System.Transactions.TransactionScopeOption.Required, transactionOption))
                //                {
                //                    //if (dsThree != null)
                //                    //{
                //                    //    using (Epm.AppLogic.Framework.CustBizObject objtem1 = new Epm.AppLogic.Framework.CustBizObject(dsThree.Tables[0], "", "LEVEL_THREE_ID"))
                //                    //    {
                //                    //        objtem1.Update(dsThree);
                //                    //    }
                //                    //}

                //                    //if (dsTwo != null)
                //                    //{
                //                    //    using (Epm.AppLogic.Framework.CustBizObject objtem1 = new Epm.AppLogic.Framework.CustBizObject(dsTwo.Tables[0], "", "CT_LEVEL_TWO_ID"))
                //                    //    {

                //                    //        objtem1.Update(dsTwo);
                //                    //    }
                //                    //}

                //                    using (Epm.AppLogic.Framework.CustBizObject objtem1 = new Epm.AppLogic.Framework.CustBizObject(ds.Tables[0], "", "GOODS_ID"))
                //                    {
                //                        if (!string.IsNullOrEmpty(strDelOneRowId))
                //                        {
                //                            objtem1.DataObj.ExecuteBySQL("DELETE B FROM SHP_COMMERCIAL_GOODS_LEVEL_TWO A LEFT OUTER JOIN SHP_COMMERCIAL_GOODS_LEVEL_THREE B ON A.CT_LEVEL_TWO_ID=B.CT_LEVEL_TWO_ID WHERE A.GOODS_ID IN ('" + strDelOneRowId.Replace(",", "','") + "')");
                //                            objtem1.DataObj.ExecuteBySQL("DELETE A FROM SHP_COMMERCIAL_GOODS_LEVEL_TWO A  WHERE A.GOODS_ID IN ('" + strDelOneRowId.Replace(",", "','") + "')");
                //                        }
                //                        objtem1.Update(ds);
                //                    }


                                     
                //                    ds.AcceptChanges();

                //                    ts.Complete();
                //                    ts.Dispose();

                //                    this.ExecJScript("layer.msg('成功保存一级分类！',1,{type:1,shade:false});");
                //                }
                //            }
                //        }
                //    }
                //    catch (Exception err)
                //    {
                //        ds.RejectChanges();
                //        gtGridRetSaveException = err.Message;
                //    }
                //}
                //if (gtGridRetSaveSuccess && (this.gtGridRet.action == "save" || strAction == "btnSave"))//根据传入的回调类型进行处理，这里响应编辑按钮
                //{
                //    //保存后将页面置为查看状态
                //    SetMode("EDIT");
                //}
            }
            else if (strAction == "btnConfirm")//根据传入的回调类型进行处理，这里响应编辑按钮
            {
                SetItemStatus(this.GetParamHtValue("CHECK_ID"), "1");
                this.ExecJScript("btnDo('mFinder');");
            }
            else if (strAction == "btnCancel")//根据传入的回调类型进行处理，这里响应编辑按钮
            {
                SetItemStatus(this.GetParamHtValue("CHECK_ID"), "0");
                this.ExecJScript("btnDo('mFinder');");
            }
            else if (strAction == "btnDelete")//根据传入的回调类型进行处理，这里响应编辑按钮
            {
                SetItemStatus(this.GetParamHtValue("CHECK_ID"),"9");
                this.ExecJScript("btnDo('mFinder');");
            }
            else if (strAction == "btnRecommend")//根据传入的回调类型进行处理，这里响应编辑按钮
            {
                doRecommendItem(this.GetParamHtValue("CHECK_ID"), true);
                this.ExecJScript("btnDo('mFinder');");
            }
            else if (strAction == "btnCnlRecommend")//根据传入的回调类型进行处理，这里响应编辑按钮
            {
                doRecommendItem(this.GetParamHtValue("CHECK_ID"), false);
                this.ExecJScript("btnDo('mFinder');");
            }
            else if (strAction == "btnSetScore")//根据传入的回调类型进行处理，这里响应编辑按钮
            {
                SetScore(this.GetParamHtValue("CHECK_ID")); 
            }
            else if (strAction == "dobtnSetScore")//根据传入的回调类型进行处理，这里响应编辑按钮
            {
                dobtnSetScore(this.GetParamHtValue("CHECK_ID"), this.GetParamHtValue("txtSetScoreQty")); 
            }

            base.InitialByParam();
        }
        private void SetScore(string strIds)
        {
            using (msBsc.AppLogic.DataAlc.CBizShpCommercialTenantInfo oCBizShpGoodsInfo = new AppLogic.DataAlc.CBizShpCommercialTenantInfo())
            { 
                DataSet ds = oCBizShpGoodsInfo.DataObj.QueryBySQL("SELECT GOODS_QTY=SUM(A.GOODS_QTY) FROM SHP_GOODS_NORMS_PUBLIC A WHERE A.GOODS_ID IN ('" + strIds.Replace(",","','") + "')");
                if (ds.Tables[0].Rows.Count > 0)
                {
                    this.ExecJScript("$('#spnSelGoodsQty').html('" + ds.Tables[0].Rows[0]["GOODS_QTY"].ToString() + "');");
                }
                this.ExecJScript("$('#spnAllowUseScoreQty').html('" + oCBizShpGoodsInfo.GetShopScoreAllowUseQty(this.oUserInfo.OperDealerId.Split(',')[0]).ToString() + "');");
                this.ExecJScript("ShowForm();");
            }
        }
        private void dobtnSetScore(string strIds, string strScoreQty)
        {
            int iInpQty = 0;
            if (strScoreQty == string.Empty || !int.TryParse(strScoreQty, out iInpQty))
            {
                throw new Exception("请输入正确的积分数量！");
            }
            System.Transactions.TransactionOptions transactionOption = new System.Transactions.TransactionOptions();
            transactionOption.IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted;
            transactionOption.Timeout = new TimeSpan(0, 10, 0);
            using (System.Transactions.TransactionScope ts = new System.Transactions.TransactionScope(System.Transactions.TransactionScopeOption.Required, transactionOption))
            {
                using (msBsc.AppLogic.DataAlc.CBizShpGoodsInfo oCBizShpGoodsInfo = new AppLogic.DataAlc.CBizShpGoodsInfo())
                {
                    using (msBsc.AppLogic.DataAlc.CBizShpCommercialTenantInfo oCBizShpCommercialTenantInfo = new AppLogic.DataAlc.CBizShpCommercialTenantInfo())
                    {

                        DataSet ds = oCBizShpGoodsInfo.SelectByIds(strIds);
                        if (ds.Tables[0].Rows.Count <= 0)
                        {
                            throw new Exception("请选择商品记录！");
                        }
                        for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                        {
                            ds.Tables[0].Rows[i]["SCORE_NUM"] = iInpQty;
                        }
                        oCBizShpGoodsInfo.Update(ds);

                        int iAllowQty = oCBizShpCommercialTenantInfo.GetShopScoreAllowUseQty(this.oUserInfo.OperDealerId.Split(',')[0]);
                        if (iAllowQty < 0)
                        {
                            throw new Exception("积分设置错误，当前账户的积分不够用，请充值后使用该功能！");
                        }
                        this.ExecJScript("layerform && layer.close(layerform);");
                        this.ExecJScript("btnDo('mFinder');");
                    }
                }
                ts.Complete();
            }
        }

        private void SetItemStatus(string strIds, string strStatus)
        {
            using (msBsc.AppLogic.DataAlc.CBizShpGoodsInfo oCBizShpGoodsInfo = new AppLogic.DataAlc.CBizShpGoodsInfo())
            {
                DataSet ds = oCBizShpGoodsInfo.SelectByIds(strIds);
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    if (ds.Tables[0].Rows[i]["GOODS_STATUS_SID"].ToString() != strStatus)
                    {
                        ds.Tables[0].Rows[i]["GOODS_STATUS_SID"] = strStatus;
                    }
                }
                if (ds.HasChanges())
                {
                    System.Transactions.TransactionOptions transactionOption = new System.Transactions.TransactionOptions();
                    transactionOption.IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted;
                    transactionOption.Timeout = new TimeSpan(0, 10, 0);
                    using (System.Transactions.TransactionScope ts = new System.Transactions.TransactionScope(System.Transactions.TransactionScopeOption.Required, transactionOption))
                    {
                        oCBizShpGoodsInfo.Update(ds);
                        ds.AcceptChanges();

                        ts.Complete();
                        ts.Dispose(); 
                    }
                }
            }
        }

        private void doRecommendItem(string strIds ,bool blRecommend)
        {
            using (msBsc.AppLogic.DataAlc.CBizShpGoodsInfo oCBizShpGoodsInfo = new AppLogic.DataAlc.CBizShpGoodsInfo())
            {
                DataSet ds = oCBizShpGoodsInfo.SelectByIds(strIds);
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    ds.Tables[0].Rows[i]["IS_RECOMMEND"] = blRecommend;
                }
                if (ds.HasChanges())
                {
                    //System.Transactions.TransactionOptions transactionOption = new System.Transactions.TransactionOptions();
                    //transactionOption.IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted;
                    //transactionOption.Timeout = new TimeSpan(0, 10, 0);
                    //using (System.Transactions.TransactionScope ts = new System.Transactions.TransactionScope(System.Transactions.TransactionScopeOption.Required, transactionOption))
                    //{
                        oCBizShpGoodsInfo.Update(ds);
                        ds.AcceptChanges();

                        //ts.Complete();
                        //ts.Dispose(); 
                    //}
                }
            }
        }

        //获取数据原,"DP_DATA"字符一定不要改变，否则系统不能自动清除缓存
        public DataSet GetDisplayData(string strgtGridID, string strSrcF, string strsRadom)
        {
            if (strgtGridID == "myGrid1")
            {
                DataSet ds;
                if (strSrcF == "mFinder" || !this.SessionIsExists(strsRadom + "DP_DATA", "1"))//点击查询按钮时，或需要数据而没有缓存时，根据条件取出数据记录
                { 
                    using (msBsc.AppLogic.DataAlc.CBizShpGoodsInfo oCDbAccess = new msBsc.AppLogic.DataAlc.CBizShpGoodsInfo())
                    {
                        ds = oCDbAccess.SelectForDealerList(this.oUserInfo.OperDealerId.Split(',')[0], this.GetParamHtValue("GOODS_NME"), this.GetParamHtValue("GOODS_STATUS_SID"),"0"); 
                    }
                    ds.AcceptChanges();
                    SetSession(strsRadom + "DP_DATA", ds, "1");
                }
                else
                {
                    ds = (DataSet)this.GetSession(strsRadom + "DP_DATA", "1");
                }
                return ds;
            }
            else
            {
                return null;
            }
        }

    }
}